package socket;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: fzykd
 * Date: 2022-10-29
 * Time: 18:01
 */

public class TcpEchoClient {
    //网络编程大前提 客户端
    private Socket socket = null;

    //构造函数指定服务器地址
    public TcpEchoClient(String IP,int port) throws IOException {
        socket = new Socket(IP,port);
    }

    //启动客户端
    public void start(){
        System.out.println("与服务器连接成功!");
        //从控制台输入
        Scanner scanner = new Scanner(System.in);
        try(InputStream inputStream = socket.getInputStream()){
            try(OutputStream outputStream = socket.getOutputStream()){
                while (true){
                    //从控制台获取输入的字符串
                    System.out.println("->");
                    String request = scanner.next(); //next遇到空格结束
                    //2.根据字符串 构造请求 把请求发给服务器
                    PrintWriter printWriter = new PrintWriter(outputStream);
                    printWriter.println(request);
                    printWriter.flush();
                    //读取服务器返回的响应 并解析
                    Scanner respScanner = new Scanner(inputStream);
                    String response = respScanner.next();
                    //输出结构
                    System.out.printf("req: %s, resp: %s\n", request, response);
                }
            }
        }catch (IOException e){
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws IOException {
        TcpEchoClient client = new TcpEchoClient("127.0.0.1",9090);
        client.start();
    }
}
